var express = require('express');
var router = express.Router();
const userService = require('../service/userService');
const jwt = require("jsonwebtoken");
const {secretKey} = require('../token');

var fetch = require('node-fetch');
const https = require("https");
const {base64_decode} = require('../utils/file.js');
const { v4: uuidv4 } = require('uuid');
const httpsAgent = new https.Agent({rejectUnauthorized: false});

const APP_ID = 'wx457004f898a98ca0';
const SECRET = 'cca7178937814f2feba4260310a94e9f';
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send("callback('respond with a resource')");
});

router.post('/reg',async function(req,res){
  let {username,pwd} = req.body;
  let data = await userService.insert({username,pwd});
  res.send(data);
});

router.post('/login',async function(req,res){
  let {username,pwd} = req.body;
  let data = await userService.findByUsernameAndPwd({username,pwd});
  if(data.length > 0){
    let authToken = jwt.sign({data:data[0]}, secretKey);
    // req.session.user = data[0];
    res.send({status:1,token:authToken});
    // res.send({status:1});
  }else{
    res.send({status:0});
  }
});

router.post('/usernameExist',async function(req,res){
  let {username} = req.body;
  let data = await userService.findByUsername(username);
  if(data.length > 0){
    res.send({status:0});
  }else{
    res.send({status:1});
  }
});

router.get('/weixinLogin',async function(req,res){
  let code = req.query.code;
  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APP_ID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
  console.log("url",url);
  try{
    let fetchResult = await fetch(url,{
      agent: httpsAgent
      });
    let data = await fetchResult.json();
    console.log('data',url,data)
    if(!data.errcode){
      let user = await userService.findByUsername(data.openid);
      if(Object.keys(user).length > 0){
        res.send(user);
      }else{
        let newUser = await userService.insert({username:data.openid,pwd:''});
        res.send(newUser);
      }
    }else{
      res.send({});
    }
  }catch(e){
    console.log("error:",e);
    res.send({});
  }
  
});
router.post('/weixinDetail/:id', async function(req,res){
  let id = req.params.id;
  let {nickname,image} = req.body;

  let user = await userService.findById(id);
  if(image){
    let strUUID = uuidv4();
    // 把头像转存成文件
    base64_decode(image,"./public/images/"+strUUID+".jpeg");
    user.headImg = strUUID+".jpeg";
  }
  if(nickname){
    user.nickname = nickname;
  }
  await userService.update(user);
  res.send(user);
})

module.exports = router;
